package com.os.opencv.java.chapter13;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.highgui.HighGui;
import org.opencv.imgproc.Imgproc;
import org.opencv.video.BackgroundSubtractorKNN;
import org.opencv.video.Video;
import org.opencv.videoio.VideoCapture;

public class KnnBG {

    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

        //打开时视屏文件
        VideoCapture vc = new VideoCapture();
        vc.open("pics/2023-11-29_19-50-14.mp4");

        //视屏打开失败时的处理
        if(!vc.isOpened()){
            System.out.println("unable to load video!");
            return;
        }

        //创建backgroundsubstractorKnn对象
        BackgroundSubtractorKNN knn = Video.createBackgroundSubtractorKNN();

        //设置结构元素
        Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(3,3));
        Mat frame = new Mat();
        Mat fgmask = new Mat();

        while(true){
            //读取一帧视屏
            vc.read(frame);
            //如果视屏文件读完，则退出循环
            if(frame.empty()){
                break;
            }

            //获取前景
            knn.apply(frame, fgmask, -1);

            //形态学操作改善效果
            Imgproc.morphologyEx(fgmask, fgmask, Imgproc.MORPH_CLOSE, kernel);
            Imgproc.dilate(fgmask, fgmask, kernel);
            Imgproc.threshold(fgmask, fgmask, 20, 255, Imgproc.THRESH_BINARY);

            //在视屏帧上消除背景
            for(int i=0, r=fgmask.rows(); i<r; i++){
                for(int j=0, c=fgmask.cols(); j<c; j++){
                    if(fgmask.get(i, j)[0] <= 150){
                        frame.put(i, j, 255, 255, 255);
                    }
                }
            }

            //在屏幕上显示前景
            HighGui.imshow("frame", frame);
            int keyBoard = HighGui.waitKey(100);

            //按esc键，则退出
            if(keyBoard == 27){
                break;
            }
        }
        vc.release();
        System.exit(0);
    }
}
